package com.bw.login.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.path.RouterPath
import com.bw.common.event.CustomEvent
import com.bw.common.utils.DialogUtils
import com.bw.common.view.BaseMvvmActivity
import com.bw.common.vm.BaseViewModel
import com.bw.login.R
import com.bw.login.databinding.ActivityLoginBinding
import com.bw.login.vm.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import kotlin.random.Random
@Route(path = RouterPath.PATH_LOGIN_PAGE)
@AndroidEntryPoint
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding>() {
    private val mViewModel :LoginViewModel by viewModels()
    private var mValueAnimator:ValueAnimator? = null
    private var mCountValue = 0

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun initViews() {
        super.initViews()
        //登录页面
        mDataBinding.includeLoginLayout.run {
            //登录
            tvLoginBtn.setOnClickListener {
                loginToServer()
            }
            //注册
            tvRegisterNew.setOnClickListener {
                mDataBinding.cltLogin.visibility = View.GONE
                mDataBinding.cltRegister.visibility = View.VISIBLE
            }
            //忘记密码
            tvPwdForget.setOnClickListener {
                ToastUtils.showLong("忘记密码")
            }
        }

        //注册页面
        mDataBinding.includeRegisterLayout.run {
            //验证码
            tvVerifyCode.setOnClickListener {
                getPhoneVerifyCode()
            }
            //注册
            tvRegisterBtn.setOnClickListener {
                registerToServer()
            }
            //已有账号
            tvGotoLogin.setOnClickListener {
                mDataBinding.cltLogin.visibility = View.VISIBLE
                mDataBinding.cltRegister.visibility = View.GONE
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mDataBinding.root.postDelayed({
            EventBus.getDefault().postSticky(CustomEvent("HomeFragment", 1, 100))

        }, 2000)
    }
    /**
     * Android中三种动画：帧动画，补间动画和属性动画
     * 帧动画：使用xml定义一组图片，性能差，对内存消耗较大（不推荐）
     * 补间动画：指定关键帧，其他路径上动画帧交给系统提供差值器，不会改变组件原来属性（位置，大小，颜色等）
     * 属性动画：使用ObjectAnimator和ValueAnimator, 前者作用在View对象，后者作用于摸某一个值的变化
     */

    //登录
    private fun loginToServer(){
        DialogUtils.showLoading(this@LoginActivity,"登录中...")
        val userName = mDataBinding.includeLoginLayout.edtUserName.text.toString().trim()
        val passWord = mDataBinding.includeLoginLayout.edtPassWold.text.toString().trim()
        //发起登录
        if (!userName.isNullOrEmpty()&&!passWord.isNullOrEmpty()){
            mViewModel.loginToServer(userName,passWord)
        }else{
            ToastUtils.showLong("账号或密码不能为空")
        }
    }

    //获取验证码
    private fun getPhoneVerifyCode(){
        //创建属性动画
        mValueAnimator = ValueAnimator.ofInt(15,0).apply {
            duration = 15000
            interpolator = LinearInterpolator()//线性匀速差值器
            //监听动画值的变化
            addUpdateListener {
                var count = it.animatedValue as Int //可能产生一样数字
                if (count != mCountValue){
                    mCountValue = count
                    mDataBinding.includeRegisterLayout.tvVerifyCode.text = "${mCountValue}秒重新获取"
                }
            }
            //动画状态监听
            addListener(object :AnimatorListenerAdapter(){
                override fun onAnimationEnd(animation: Animator) {
                    //使用随机数生成6位数验证码
                    val verifyCode = Random.nextInt(900000)+100000
                    mDataBinding.includeRegisterLayout.edtVerifyCode.setText("${verifyCode}")
                    mDataBinding.includeRegisterLayout.tvVerifyCode.text = "获取验证码"
                }
            })
        }
        //启动动画
        mValueAnimator?.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消动画并标识为可回收对象
        mValueAnimator?.cancel()
        mValueAnimator = null
    }

    private fun registerToServer(){
        DialogUtils.showLoading(this@LoginActivity,"注册中...")

        val userName = mDataBinding.includeRegisterLayout.edtPhoneNum.text.toString().trim()
        val passWord = mDataBinding.includeRegisterLayout.edtPwd.text.toString().trim()
        val repassword = mDataBinding.includeRegisterLayout.edtRePwd.text.toString().trim()
        //手机号校验
        if (!RegexUtils.isMobileSimple(userName)){
            ToastUtils.showLong("请输入正确的手机号！！")
            return
        }
        //校验两次输入的密码是否一致
        if (passWord!=repassword){
            ToastUtils.showLong("您输入的密码不一致！！")
            return
        }
        //发起注册
        mViewModel.registerToServer(userName,passWord)
    }


    override fun observeDataChanged() {
        mViewModel.mError.observe(this@LoginActivity){
            //关闭Loading
            DialogUtils.dismissLoading()

            ToastUtils.showLong(it)
        }
        //登录和注册成功订阅
        mViewModel.mLoginSuccess.observe(this@LoginActivity){
            //关闭Loading
            DialogUtils.dismissLoading()
            //注册成功业务
            if (it.typeId == 0){
                ToastUtils.showLong("注册成功")
                //清除输入框
                mDataBinding.includeRegisterLayout.run {
                    edtPhoneNum.setText("")
                    edtVerifyCode.setText( "")
                    edtPwd.setText("")
                    edtRePwd.setText("")
                }
                //切换到登录页面
                mDataBinding.cltRegister.visibility = View.GONE
                mDataBinding.cltLogin.visibility = View.VISIBLE

                //回显新账号和密码
                mDataBinding.includeLoginLayout.edtUserName.setText(it.username)
                mDataBinding.includeLoginLayout.edtPassWold.setText(it.password)

            }
            //登录成功
            if (it.typeId == 1){
                ToastUtils.showLong("登录成功")
                //调到主页面
                ARouter.getInstance().build(RouterPath.PATH_MAIN_PAGE).navigation()

                //给首页发送事件
                EventBus.getDefault().post(CustomEvent(target = "HomeFragment", data = it.id, type = 100))
                //关闭登录页面
                this@LoginActivity.finish()
            }
        }
    }

}